﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Web.Security;
using System.Web;

namespace SSCCMembership.Web.Services
{
    [ErrorHandlerBehavior]
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class LoginService
    {
        //ASC.LoginAsync(txtUsername.Text, txtPassword.Password, null, false, txtUsername.Text);
        [OperationContract]
        public CanFail<bool> Login(string Username, string Password, string CustomCredential, bool isPersistent)
        {
            try
            {
                if (Membership.ValidateUser(Username, Password))
                {
                    ErrorHandlerBehavior.Log("Log in - " + Username);
                    //ErrorHandlerBehavior.Log("Attempting to store cookie for - " + Username);
                    FormsAuthentication.SetAuthCookie(Username, isPersistent);
                    //ErrorHandlerBehavior.Log("Stored cookie for - " + Username);
                    return new CanFail<bool>() { Success=true, Value=true };
                }
                else
                {
                    ErrorHandlerBehavior.Log("Failed Log in - " + Username);
                    return new CanFail<bool>() { Success = true, Value = false };
                }
            }
            catch (Exception ex)
            {
                try
                {
                    ErrorHandlerBehavior.Log(ex.ToString());
                    
                }
                catch (Exception ex2)
                {
                    return new CanFail<bool>() { Success = false, FailureMessage = ex2.Message };
                }
                throw ex;
            }


        }

        [OperationContract]
        public bool IsLoggedIn()
        {
            return HttpContext.Current.User.Identity.IsAuthenticated;
        }

        // Add more operations here and mark them with [OperationContract]
    }
    public class CanFail<T>
    {
        public bool Success { get; set; }
        public T Value { get; set; }
        public string FailureMessage { get; set; }
    }
}